﻿#include "imgprocesswidget.h"
#include "ui_imgprocesswidget.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QDirIterator>
#include <QDir>
#include <QFileInfo>
#include "ImageProcess.h"

ImgProcessWidget::ImgProcessWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ImgProcessWidget)
{
    ui->setupUi(this);
    m_source = "";
    m_target = "";
    this->setWindowTitle(QStringLiteral("图像处理"));
}

ImgProcessWidget::~ImgProcessWidget()
{
    delete ui;
}

void ImgProcessWidget::on_selectimgs_clicked()
{
    QString folder_path = QFileDialog::getExistingDirectory(this,QStringLiteral("选择源文件夹"),"");
    if(folder_path.isEmpty()){
        m_source = "";
        return;
    }
    m_source = folder_path;
}

void ImgProcessWidget::on_selectsave_clicked()
{
    QString folder_path = QFileDialog::getExistingDirectory(this,QStringLiteral("选择目标文件夹"),"");
    if(folder_path.isEmpty()){
        m_target = "";
        return;
    }
    m_target = folder_path;
}

void ImgProcessWidget::on_start_clicked()
{
    if(m_source.isEmpty()){
        QMessageBox::about(NULL,"",QStringLiteral("还未选择源文件目录"));
        return;
    }
    else if(m_target.isEmpty()){
        QMessageBox::about(NULL,"",QStringLiteral("还未选择目标文件目录"));
        return;
    }
    Process();
}

void ImgProcessWidget::Process()
{
    CImageProcess process;
    QStringList dirlist;
    dirlist << m_source;
    QString curdir = "";
    QDir dir;
    while(dirlist.size()){
        curdir = dirlist.first();
        //QMessageBox::about(NULL,"",curdir);
        dirlist.pop_front();
        QDirIterator it(curdir,QDir::Files|QDir::Dirs|QDir::NoDotAndDotDot);	//遍历所有目录和文件
        while (it.hasNext())//存在
        {
            QString name = it.next();//读取
            QFileInfo info(name);
            if (info.isDir())//判断是目录
            {
                dirlist << info.filePath();
                //QMessageBox::about(NULL,"",dirlist.last());
                continue;
            }
            else
            {
                if (info.suffix() == "jpg" || info.suffix() == "bmp" || info.suffix() == "png")
                {
                    string source = (curdir + "/" + info.fileName()).toLocal8Bit().data();
                    //QMessageBox::about(NULL,"",source.c_str());
                    QString path = QString(curdir).replace(m_source,m_target);
                    dir.mkpath(path);
                    string target = ( path + "/" + info.fileName()).toLocal8Bit().data();
                    //QMessageBox::about(NULL,"",target.c_str());
                    process.image_process(source,target);
                }
            }
        }
    }
    QMessageBox::about(NULL,"",QStringLiteral("完成"));
}
